import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Param,
  Delete,
  BadRequestException,
  Header
} from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { WorkflowService } from './workflow.service';
import { CreateWorkflowDto, UpdateWorkflowDto } from './dto/workflow.dto';
import { Logger } from '@nestjs/common';

@ApiTags('工作流')
@Controller('v1/workflows')
export class WorkflowController {
  private readonly logger = new Logger(WorkflowController.name);

  constructor(private readonly workflowService: WorkflowService) { }

  @Post()
  @ApiOperation({ summary: '创建工作流' })
  @Header('Content-Type', 'application/json')
  async create(@Body() createWorkflowDto: CreateWorkflowDto) {
    try {
      const result = await this.workflowService.create(createWorkflowDto);
      return {
        success: true,
        data: result,
        message: '创建成功'
      };
    } catch (error) {
      this.logger.error('Create workflow failed:', error);
      throw new BadRequestException({
        success: false,
        message: error instanceof Error ? error.message : '创建失败'
      });
    }
  }

  @Get()
  @ApiOperation({ summary: '获取工作流列表' })
  @Header('Content-Type', 'application/json')
  async findAll() {
    try {
      const result = await this.workflowService.findAll();
      return {
        success: true,
        data: result
      };
    } catch (error) {
      throw new BadRequestException({
        success: false,
        message: error.message || '获取列表失败'
      });
    }
  }

  @Get(':id')
  @ApiOperation({ summary: '获取工作流详情' })
  @Header('Content-Type', 'application/json')
  async findOne(@Param('id') id: string) {
    try {
      const result = await this.workflowService.findOne(id);
      return {
        success: true,
        data: result
      };
    } catch (error) {
      throw new BadRequestException({
        success: false,
        message: error.message || '获取详情失败'
      });
    }
  }

  @Put(':id')
  @ApiOperation({ summary: '更新工作流' })
  @Header('Content-Type', 'application/json')
  async update(@Param('id') id: string, @Body() updateWorkflowDto: UpdateWorkflowDto) {
    // this.logger.debug('更新请求数据:', {
    //   id,
    //   dto: {
    //     ...updateWorkflowDto,
    //     workflow_json: '...' // 避免日志过大
    //   }
    // });

    try {
      const result = await this.workflowService.update(id, updateWorkflowDto);
      return {
        success: true,
        data: result,
        message: '更新成功'
      };
    } catch (error) {
      this.logger.error('更新失败:', {
        error: error.message,
        stack: error.stack,
        dto: updateWorkflowDto
      });
      throw new BadRequestException(error.message);
    }
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除工作流' })
  @Header('Content-Type', 'application/json')
  async remove(@Param('id') id: string) {
    try {
      await this.workflowService.remove(id);
      return {
        success: true,
        message: '删除成功'
      };
    } catch (error) {
      throw new BadRequestException({
        success: false,
        message: error.message || '删除失败'
      });
    }
  }

  @Post(':id/execute')
  @ApiOperation({ summary: '执行工作流' })
  async execute(
    @Param('id') id: string,
    @Body() params: Record<string, any>
  ) {
    try {
      return await this.workflowService.execute(id, params);
    } catch (error) {
      throw new BadRequestException(error.message);
    }
  }

  @Post('generate')
  @ApiOperation({ summary: '生成图片' })
  async generateImage(@Body() data: { workflow_id: string; params: any }) {
    try {
      const { workflow_id, params } = data;

      // 记录请求参数
      this.logger.debug('Generate image request:', { workflow_id, params });

      const result = await this.workflowService.generateImage(workflow_id, params);

      if (!result.success) {
        throw new BadRequestException(result.message);
      }

      return result;
    } catch (error) {
      this.logger.error('Generate image failed:', error);
      if (error instanceof BadRequestException) {
        throw error;
      }
      throw new BadRequestException(
        error instanceof Error ? error.message : '生成失败'
      );
    }
  }

  @Get('generate/status/:promptId')
  @ApiOperation({ summary: '获取生成状态' })
  async getGenerationStatus(@Param('promptId') promptId: string) {
    try {
      const status = await this.workflowService.checkGenerationStatus(promptId);
      return {
        success: true,
        data: status
      };
    } catch (error) {
      throw new BadRequestException(error.message);
    }
  }

  @Get('status/:promptId')
  @ApiOperation({ summary: '获取生成状态（备用路径）' })
  async getStatus(@Param('promptId') promptId: string) {
    return this.getGenerationStatus(promptId);
  }
} 